package com.ems.sys.service.impl;

import com.ems.sys.dao.RoleMapper;
import com.ems.sys.dao.UserDataMapper;
import com.ems.sys.pojo.Role;
import com.ems.sys.pojo.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDataServiceImpl implements UserDetailsService {
    private static String key;

    @Autowired
    private UserDataMapper userDataMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //这是通过username查询获取一组数据将获得的数据传给security的User

        //sql语句自己写
        Users user = userDataMapper.selectByUsername(username);
        List<Role> roleList = roleMapper.findRoleByUserId(user.getuId());
        List<SimpleGrantedAuthority> list = roleList.stream().map(authority -> new SimpleGrantedAuthority(authority.getRoleName()))
                .collect(Collectors.toList());
        if (user == null) {
            throw new UsernameNotFoundException("该用户不存在！");
        }

        return new User(user.getUsername(),user.getPassword(),list);
    }
}
